<?php

namespace Yolo\Components\ApplicationRegistry;

use ReflectionException;
use Yolo\ComponentManager\AbstractComponent;
use Yolo\Di\DI;
use Yolo\Di\Errors\CircularDependencyException;
use Yolo\Di\Errors\InvalidAttributeException;
use Yolo\Di\Errors\ParameterTypeEmptyException;
use Yolo\Errors\ConfigInvalidException;
use Yolo\Observers\ObserverHelper;
use Yolo\Service\ApplicationContainer;

class ApplicationRegistryComponent extends AbstractComponent
{
    public function __construct(
        private readonly ApplicationContainer $container,
    ){}

    /**
     * Register the component.
     * @return void
     * @throws ConfigInvalidException
     */
    public function register(): void
    {
        $config = $this->container->getConfig()->get('applicationRegistry');
        if (!($config['enabled'] ?? false)) {
            return;
        }

        // 此处检查配置是否正确
        $url = $this->container->getConfig()->getClientConnection(ApplicationRegistry::SERVICE_NAME);
        if (!$url) {
            throw new ConfigInvalidException('Config rpc.client.connections.' . ApplicationRegistry::SERVICE_NAME . ' not found');
        }

        $instance = $this->container->getConfig()->get('rpc.server.instance');
        if (empty($instance['http'])) {
            throw new ConfigInvalidException('Config rpc.server.instance.http not found');
        }
    }

    /**
     * Called when all components are registered.
     * @return void
     * @throws CircularDependencyException
     * @throws ParameterTypeEmptyException
     * @throws ReflectionException|InvalidAttributeException
     */
    public function registered(): void
    {
        $observerHelper = DI::use(ObserverHelper::class);
        $observerHelper->subscribe(
            AfterWorkerStartedObserver::class
        );
    }
}
